//
//  NetworkTool.swift
//  Weibo
//
//  Created by 唐润欣 on 16/6/18.
//  Copyright © 2016年 唐润欣. All rights reserved.
//

import Foundation
import AFNetworking

//定义请求方式枚举
enum RequsetType: String {
    
    case GET = "GET"
    case POST = "POST"
}

let appKey = "1869565533"
let appSecret = "b9ab1865237749d8c92621ffb9466266"
let redirectURL = "https://www.baidu.com"

//发生该错误的原因是因为用闭包初始化一个对象时，没有指定其类型：Cannot invoke closure of type '() -> _' with an argument list of type '()'
class NetworkTool: AFHTTPSessionManager {
    
    //网络中间层的单例
    static let sharedTool: NetworkTool = {
        
        let tool = NetworkTool(baseURL: nil)
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    /**
     调用AFHttpSessionManager的方法请求网络数据
     
     - parameter url 请求地址
     - parameter method 请求方式
     - parameter parameters 请求的参数
     - parameter callBack 请求完成后回调的闭包
     */
    func request(url: String, method: RequsetType, parameters: [String: AnyObject]?, callBack: ([String: AnyObject]?) ->()) {
        
        let success = { (task:NSURLSessionDataTask, response: AnyObject?) ->Void in
            
            //说有response有返回值
            if let response = response {
                
                //如果afn返回的数据可能转成字典，就可以直接返回给调用者
                if let responseDic = response as? [String: AnyObject] {
                    
                    callBack(responseDic)
                    
                    //说明有返回值，但是数据格式不正确
                } else {
                    
                    //callBack nil 通知用户，请求不成功
                    print("请求数据格式不正确")
                    callBack(nil)
                }
                
                //说明没有返回值
            } else {
                
                callBack(nil)
            }
        }
        
        //AFN请求失败回调
        let failure = { (task: NSURLSessionDataTask?, error: ErrorType) ->Void in
            
            print(error)
            callBack(nil)
        }
        
        if method == .GET {
            
            GET(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        if method == .POST {
            
            POST(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
